// pages/pets/pets.js
const {
  getRecommentPetsList
} = require('../../api/pets')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    background: ['http://localhost:3000/bg10.jpg', 'http://localhost:3000/bg9.jpg'],
    petsList: [],
    total: 1,
    page: 1,
    pageList:[1],
    show: false
  },
  showPopup() {
    this.setData({ show: true });
    console.log(this.data);
  },

  onClose() {
    this.setData({ show: false });
    console.log(this.data);

  },
  goDetail(event) {
    // console.log(event.currentTarget.dataset.id);
    wx.navigateTo({
      url: `/pages/petsDetail/petsDetail?id=${event.currentTarget.dataset.id}&page=${this.data.page}`,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    getRecommentPetsList(res => {
      // console.log(res);
      this.setData({
        petsList: res.data.list,
        total: Math.ceil(res.data.total / 8)
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    const index = Math.floor(Math.random() * (this.data.total-1) + 1)
    this.setData({
      page: index,
      pageList:[index]
    })
    // console.log(this.data);
    getRecommentPetsList(res => {
      // console.log(res);
      this.setData({
        petsList: res.data.list
      })
      wx.stopPullDownRefresh();
    }, this.data.page)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.pageList.find(item => item == (this.data.page + 1) % this.data.total) == undefined) {
      if (this.data.page + 1 != this.data.total) {
        const index = (this.data.page + 1) % this.data.total
        this.setData({
          pageList: [...this.data.pageList, index],
          page: index
        })
      } else {
        this.setData({
          page: this.data.page + 1,
          pageList: [...this.data.pageList, this.data.page + 1],
        })
      }
      console.log(this.data);
      getRecommentPetsList(res => {
        // console.log(res);
        this.setData({
          petsList: [...this.data.petsList, ...res.data.list]
        })
      }, this.data.page)
    }else{
      return
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})